﻿using DishOrderSystem.Models;
using DishOrderSystem.Services;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace DishOrderSystem.ViewModels
{
    class MainViewModel: BindableBase
    {
        //Command="{Binding Path=DataContext.SelectMenuItemCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}"
        public DelegateCommand SelectMenuItemCommand { set; get; }
        public DelegateCommand PlaceOrderCommand { set; get; }

        private int count;

        public int Count
        {
            get { return count; }
            set { count = value;
                this.RaisePropertyChanged("Count");
                }
        }

        private Restaurant restaurant;

        public Restaurant Restaurant
        {
            get { return restaurant; }
            set { restaurant = value;
                this.RaisePropertyChanged("Reestaurant");
            }
        }

        private List<DishMenuItemViewModel> dishMenu;

        public List<DishMenuItemViewModel> DishMenu
        {
            get { return dishMenu; }
            set { dishMenu = value;
                this.RaisePropertyChanged("DishMenu");    
            }
        }

        public  MainViewModel()
        {
            LoadRestaurant();
            LoadDishMenu();
            this.PlaceOrderCommand = new DelegateCommand(new Action(this.PlaceOrderCommandExecute));
            this.SelectMenuItemCommand = new DelegateCommand(new Action(this.SelectMenuItem));
        }

        private void LoadRestaurant()
        {
            this.Restaurant = new Restaurant();
            this.Restaurant.Name = "Crazy 大象";
            this.Restaurant.Address = "北京中南海一号";
            this.Restaurant.PhoneNumber = "188818888 or 888888";
        }

        private void LoadDishMenu()
        {
            IDataService ds = new XmlDataService();
            var dishes = ds.GetAllDishes();
            this.DishMenu = new List<DishMenuItemViewModel>();
            foreach (var dish in dishes)
            {
                DishMenuItemViewModel item = new DishMenuItemViewModel();
                item.Dish = dish;
                this.DishMenu.Add(item);
            }
        }

        private void PlaceOrderCommandExecute()
        {
            var selectedDishes = this.DishMenu.Where(i => i.IsSelected == true).Select(i => i.Dish.Name).ToList();
            IOrderService orderService = new MockOrderService();
            orderService.PlaceOrder(selectedDishes);
            MessageBox.Show("Order sucessfully!");
        }

        private void SelectMenuItem()
        {
            this.Count = this.DishMenu.Count(i => i.IsSelected == true);
            //MessageBox.Show("selected");
        }

    }
}
